package com.business.lgh.naocs.naming.core;

import com.business.lgh.naocs.naming.core.pojo.Member;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import java.lang.reflect.Array;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lgh
 * @version V1.0
 * @Package com.business.lgh.naocs.naming.core
 * @date 2020/6/28 2:43 下午
 */
@Component("serverMemberManager")
@Data
public class ServerMemberManager {

    public static final String SERVER_PORT = "server.port";
    public static final String CLUSTER_LIST = "cluster.list";

    //从confs
    Map<String, Member> serverList = new ConcurrentHashMap<>();

    //健康状态为up的
    Map<String, Member> healthList = new ConcurrentHashMap<>();

    //当前server的ip+端口地址
    final String localAddress;

    @Autowired
    public ServerMemberManager(ApplicationContext context) throws UnknownHostException {
        localAddress = getLocalAddress(context);

        //获取端口号
        ArrayList<String> clusters = loadClusterConf(context);
        clusters.stream().forEach(c -> {
            //添加成员
            String[] addressParams = c.split(":");
            Member member = new Member(addressParams[0], Integer.parseInt(addressParams[1]));
            serverList.put(c, member);
        });
    }

    /**
     * 获取集群节点
     *
     * @param context
     * @return
     */
    private ArrayList<String> loadClusterConf(ApplicationContext context) throws UnknownHostException {
        String clusterParams = context.getEnvironment().getProperty(CLUSTER_LIST);
        String[] split = clusterParams.split(",");
        split=new String[]{ InetAddress.getLocalHost().getHostAddress()+":8081", InetAddress.getLocalHost().getHostAddress()+":8082"};
        return new ArrayList<String>(Arrays.asList(split));
    }


    /**
     * 获取本地地址
     *
     * @param context
     * @return
     */
    public String getLocalAddress(ApplicationContext context) {
        //获取当前IP
        String ip = null;
        try {
            ip = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        //获取端口号
        int port = Integer.parseInt(context.getEnvironment().getProperty(SERVER_PORT, "8488"));
        return ip + ":" + port;
    }



    /**
     * @return  返回所有节点
     */
    public List<Member> members() {
        return new ArrayList<Member>(serverList.values());
    }
}
